<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/28
 * Time: 11:10
 */

namespace app\api\controller;

use think\Db;

class Ali extends Base
{
    protected $config = array(
        'partner' => '2088621781822784',//用不着
        'seller_id' => 'admin@bagepanzi.com',//用不着
        'sign_type' => 'RSA2',// 直接写死了
        'it_b_pay' => '10m',//用不着
        'md5' => 'djqm7budkdlki6a76yasuyb9s1riiu1j',//用不着
        'ali_public' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuO761rzRRShKvhNGn4Wj8Iyonu9cfYCBGTvKLJRtjTlAkr7aRgy+97cxysONrWXsypdKDSKVvzgteuKqaUOt8BHUwJLmStiDAeIYjDgIC597vRI+yoBy3sxfEKPGepMNUE14pzZY1BT08g/2Xu7n31yeWcinCPiEtjCx2oNqNvaP3zerOOelEiKhIE5FJ7dWP0UsD7Bplidx9bQFx4cqviUPSe2/5W1+EJAo1T0SMeFlveuEbLqVdamKS8DciMzNKPoUvxfuTS42te/rB3HiueUHeT96DWBDYcbiQcuKW4zzsJMLjEqSLZJJrVfON75dVxkqbjrSyXWKV29r1TxYmQIDAQAB',
        'public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAndvj1Nq5Nfh/yVAejEC5JQSB1G+i/WcqLgd93TLPieZotXUCprMCl2QDMjF28NhLiPVAQPP/qZ7+PT88qLDrY4ClWgZIBQRxvvYz8SokvJU9JbZLPqSPbDUyQzLXRV2l/QaN86Aq1y1R4XGOu2tCBMaM3V0yXERRckNnHvxa9kxHu/QtEdKgodVlOxkD1c79nCdz5rWeVIHXbr0tZYPHclDiA6iNpWgFS5OmmE9O08vL8Rj1WF2jdViyGEWrWNymFN3R86BaaBlAFHzRODW3KQJeVKWUsn/gKg2639M+cCdPfGmF9igOIk+Sn5wVQa25cI/hLlBtRZLndPpXvJywuQIDAQAB",
        'private_key' => 'MIIEowIBAAKCAQEAndvj1Nq5Nfh/yVAejEC5JQSB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3ZRqUxB09Lyopq4AtRzO9o+2Tic+AXkDwwiyJlnPMx9227nwVhZynqV+i8+T76x7ihVpyZ7nxp6SqrKIC3EK45TbLR0TdWV0HA64Unb0fECgYBhbs8z2aIacpYCTJKl2Uh4Bo+hSWa9jYVPNV+SUgfEBzJ6qpjTYwl/JQft1HwWbAbNkZCG3cReLtVLIspFJ4A0/372ed0s7OI0f4SYOQbUBf13jO3ABYWoPzc9kMsel4XgtnqiPg33tUK4W/5Fi7k9XtziFcuqemh1xeptLKqfQQKBgGhaKz4VgOPYSIO6pysnb0e8792ziRHHHAjHA2uwNWQFLkDJbGh1vffI6OJsxtdaA43BlLUAxhUM0oWttJ8SELpK6WZ0tutGbxcpUMZsGLU507P+i1k9ShzmFrJazBURn6olb00puZqgChx0RPJbmJ0e6f2cDvi0JFowv6N4LekF'
    );
    public $body;//描述
    public $subject;//描述
    public $total_amount;//金额
    public $out_trade_no;//订单号

    /**
     * @param $no
     * @param $money
     * @return string
     * 支付宝支付
     */
    public function getParam($no, $money, $body, $subject)
    {
//    public function getParam(){
        import('alipay.aop.AopClient', EXTEND_PATH);
        import('alipay.aop.request.AlipayTradeAppPayRequest', EXTEND_PATH);
//        $no = '5851546514677777712121212';
//        $no = time().rand(1000000,9999999);
//        $money = '0.01';
        try {
            $aop = new \AopClient;
            $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do?charset=utf-8";
            $aop->appId = "2021001167698015";
            $aop->rsaPrivateKey = $this->config['private_key'];
            $aop->format = "json";
            $aop->charset = "UTF-8";
            $aop->signType = "RSA2";
            $aop->alipayrsaPublicKey = $this->config['public_key'];
            $request = new \AlipayTradeAppPayRequest();
            $bizcontent = "{\"body\":\"" . $body . "\","
                . "\"subject\": \"" . $subject . "\","
                . "\"out_trade_no\": \"" . $no . "\","
                . "\"timeout_express\": \"30m\","
                . "\"total_amount\": \"" . $money . "\","
                . "\"product_code\":\"QUICK_MSECURITY_PAY\""
                . "}";
            $request->setNotifyUrl("http://app.sqstyy.com/api/Ali/huidiao");
            $request->setBizContent($bizcontent);
            $response = $aop->sdkExecute($request);
//            return $response;
            $res['msg'] = $response;
            $res['status'] = 200;
            return $res;
//            return json_encode($res);
        } catch(\Exception $e) {
            $res['msg'] = 'error';
            $res['status'] = 0;
            return $res;
        }
    }

    /**
     * 验证返回
     * @return bool
     */
    public function checkReturn()
    {
        import('alipay.aop.AopClient', EXTEND_PATH);
        $aop = new \AopClient;
        $aop->alipayrsaPublicKey = $this->config['ali_public'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if($flag) {
            return $_POST;
        } else {
            return false;
        }
    }
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    /**
     * 生成订单
     * @return string|void
     * user_id：用户ID,
     * type：1 课程购买  2 捐赠  3 打赏
     * price：打赏或捐赠的价格，当type为2或者3时传
     * activity_id：捐赠的活动ID，当type为2时，传此值
     */
    public function alipay()
    {
        extract(input());
        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == false) {
            return $this->apiError(301);
        }
            $id = input('param.id');
            $info  = Db::table('up_pay')->where('pay_id',$id)->find();
            $money = 0.01;
            $this->body = '中房缴费充值';
            $this->subject = '中房缴费充值';
            $this->total_amount = $money;
            $this->out_trade_no = $info['pay_number'];
            if($info['pay_type']==''){
                Db::table('up_pay')->where('pay_id',$id)->setField('pay_type',2);
            }
//        if($res) {
            $respont = $this->getParam($this->out_trade_no, $this->total_amount, $this->body, $this->subject);
            return json_encode($respont);
//        } else {
//            return json_encode(['status' => 0, 'msg' => '生成订单失败，请联系管理员']);
//        }
    }

    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = 'file/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = implode(' | ', $data);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo) {
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED') {
                $num = $getInfo['out_trade_no'];//订单号
                $dataOrder = array();
//           $num = '20200623161601971239375';
           Db::startTrans();
                try{
                    $info = Db::table('up_pay')->where('pay_number',$num)->find();
                    //查询这个房子的业主
                    $map['house_id'] = $info['pay_house_id'];
                    $map['xq_role'] = 2;
                    $map['xq_sh_status'] = 2;
                    $xq_user_id = Db::table('up_xq_property')->where($map)->value('xq_user_id');
                    if($info['pay_status'] == 1){
                        //推送
                        $list =$listInfo =[];
                        if($info['pay_user_id']!=''){
                            $v = (string)$info['pay_user_id'];
                            array_push($list, $v);
                            $str = '费用缴纳成功';
                            // 推送
                            try{
                                $this->Jpush(1, $list, $str, ['send_type' => 1]);
                            }catch(\Exception $e){
                            }
                        }
                        //推送
                        if($xq_user_id!=''){
                            if($info['pay_user_id']!=$xq_user_id){
                                $vv = (string)$xq_user_id;
                                array_push($listInfo, $vv);
                                $str = '费用缴纳成功';
                                // 推送
                                try{
                                    $this->Jpush(1, $listInfo, $str, ['send_type' => 1]);
                                }catch(\Exception $e){

                                }
                            }
                        }
                        //插入消息表开始
                        $map1['a.house_id'] = $info['pay_house_id'];
                        $lists = Db::name('xq_house')->alias('a')
                            ->join('up_xq ux','ux.xq_id =a.xq_id','left')
                            ->join('up_xq_block uxb','uxb.block_id =a.block_id','left')
                            ->join('up_xq_unit uxn','uxn.unit_id =a.unit_id','left')
                            ->join('up_xq_room uxr','uxr.room_id =a.room_id','left')
                            ->where($map1)
                            ->field('a.*,ux.xq_name,uxb.block_name,uxn.unit_name,uxr.room_name')
                            ->find();
                        $time = date('Y-m-d H:i:s');
                        $dataAll['n_title'] = $lists['xq_name'].'  '.$lists['block_name'].'-'.$lists['room_name'];
                        $dataAll['n_type'] = 2;
                        $dataAll['n_user_id'] = ','.$info['pay_user_id'].',';
                        $dataAll['n_read'] = ',0,';
                        $dataAll['n_delete'] = ',0,';
                        $dataAll['n_time'] = $time;
                        $dataAll['n_classify'] = 2;
                        //消息表 1物业费  2电费  3水费  4停车费   5租金缴纳
                        //订单表   1水费   2  电费   3 物业费   4 停车费  5租金缴纳
                        if($info['pay_cate']==1){//水费
                            $dataAll['n_classify_type'] = 3;
                        }elseif ($info['pay_cate']==2){
                            $dataAll['n_classify_type'] = 2;
                        }elseif ($info['pay_cate']==3){
                            $dataAll['n_classify_type'] = 1;
                        }elseif ($info['pay_cate']==4){
                            $dataAll['n_classify_type'] = 4;
                        }elseif ($info['pay_cate']==5){
                            $dataAll['n_classify_type'] = 5;
                        }
                        $dataAll['n_classify_status'] = 2;
                        $dataAll['n_money'] = $info['pay_price'];
                        Db::table('up_notice')->insert($dataAll);
                        //结束
                        $dataOrder['pay_status'] = 2;//1是未支付  2已支付
                        $dataOrder['pay_complete_time'] = date('Y-m-d H:i:s');//1是未支付  2已支付
                        $dataOrder['pay_third_num'] = $getInfo['trade_no'];//第三方交易号
//                        $dataOrder['pay_third_num'] = 1111111;//第三方交易号
                        //更新订单状态
                        Db::table('up_pay')->where('pay_number',$num)->update($dataOrder);
                        if($info['pay_cate']!=5){
                            //更新缴费状态
                            Db::table('up_xq_pay')->where('pay_id',$info['pay_xq_id'])->setField('pay_status',2);
                        }
                    }
                    Db::commit();
                    die('success');
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'error';
                }
            }
        }
    }
}